//
//  HeaderView.m
//  wtshoppingcite
//
//  Created by TW on 14-10-23.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "HeaderView.h"
#import "OtherModel.h"
#import "UIImageView+WebCache.h"
#import "UIImage+category.h"

@implementation HeaderView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       _bjImageview = [[UIImageView alloc]initWithFrame:self.bounds];
        _bjImageview.image =[UIImage imageNamed:@"beijing"];
        _bjImageview.userInteractionEnabled = YES;
        [self addSubview:_bjImageview];
        
        if ([APP_DELEGATE isLogin]) {
            
             [self _initView];
            
        }else{
            
            [self loginView];
            
        }
    }
    return self;
}

-(void)loginView{
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake( (self.width - 160)/2 , 30, 160, 20)];
    label.text = @"欢迎来到零点家园";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16.0f];
    [_bjImageview addSubview:label];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((self.width - 60)/2,label.bottom+5, 60, 30)];
    [button setTitle:@"登录/注册" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setFont:[UIFont systemFontOfSize:13.0f]];
    [button setBackgroundImage:[UIImage imageNamed:@"register_select"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(loginViewAction) forControlEvents:UIControlEventTouchUpInside];
    [_bjImageview addSubview:button];
}

- (void)_initView
{
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 60, 60)];
    _headerImageView.backgroundColor = [UIColor clearColor];
    _headerImageView.layer.cornerRadius = 30;
    _headerImageView.clipsToBounds = YES;
    _headerImageView.contentMode = UIViewContentModeScaleAspectFill;
    [_bjImageview addSubview:_headerImageView];
    _headerImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *thumbnailTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(thumbnailTapAction:)];
    [_headerImageView addGestureRecognizer:thumbnailTap];
    
    
    _nickLabel = [[UILabel alloc] initWithFrame:CGRectMake(_headerImageView.right + 20, _headerImageView.top +10, 120, 22)];
    _nickLabel.backgroundColor = [UIColor clearColor];
    //_nickLabel.textColor = UIColorFromRGB(0x9fa0a0);
    _nickLabel.textAlignment = NSTextAlignmentLeft;
    _nickLabel.font = [UIFont boldSystemFontOfSize:16];
    _nickLabel.numberOfLines = 1;
    _nickLabel.text = @"未知名";
    [_bjImageview addSubview:_nickLabel];
    
    _focusLabel = [[UILabel alloc] initWithFrame:CGRectMake(_nickLabel.left, _nickLabel.bottom +10, 40, 22)];
    _focusLabel.backgroundColor = [UIColor clearColor];
   // _focusLabel.textColor = UIColorFromRGB(0x9fa0a0);
    _focusLabel.textAlignment = NSTextAlignmentLeft;
    _focusLabel.font = [UIFont systemFontOfSize:12];
    _focusLabel.numberOfLines = 1;
    _focusLabel.text = @"积分:";
    
    [_bjImageview addSubview:_focusLabel];
    
    _focusNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(_focusLabel.right, _focusLabel.top, 40, 22)];
    _focusNumLabel.backgroundColor = [UIColor clearColor];
   // _focusNumLabel.textColor = UIColorFromRGB(0x9fa0a0);
    _focusNumLabel.textAlignment = NSTextAlignmentLeft;
    _focusNumLabel.font = [UIFont systemFontOfSize:12];
    [_bjImageview addSubview:_focusNumLabel];
    
    
    _fansLabel = [[UILabel alloc] initWithFrame:CGRectMake(_focusNumLabel.right + 5,_focusNumLabel.top, 40, 22)];
    _fansLabel.backgroundColor = [UIColor clearColor];
   // _fansLabel.textColor = UIColorFromRGB(0x9fa0a0);
    _fansLabel.textAlignment = NSTextAlignmentLeft;
    _fansLabel.text = @"等级:";
    _fansLabel.font = [UIFont systemFontOfSize:12];
    _fansLabel.numberOfLines = 1;
    [_bjImageview addSubview:_fansLabel];
    
    
    _iconImage = [[UIImageView alloc]initWithFrame:CGRectMake(_fansLabel.right, _focusNumLabel.top+3, 15, 15)];
    _iconImage.image = [UIImage imageNamed:@"level"];
    [_bjImageview addSubview:_iconImage];
    
//    _fansNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(_fansLabel.right + _iconImage.width, _fansLabel.top, 66, 22)];
//    _fansNumLabel.backgroundColor = [UIColor clearColor];
//    _fansNumLabel.textColor = UIColorFromRGB(0x9fa0a0);
//    _fansNumLabel.textAlignment = NSTextAlignmentLeft;
//    _fansNumLabel.text = @"贫农";
//    _fansNumLabel.font = [UIFont systemFontOfSize:12];
//    _fansNumLabel.numberOfLines = 1;
//    [self addSubview:_fansNumLabel];
    
    UIView *seperateView = [[UIView alloc]initWithFrame:CGRectMake(0,self.height - 10, kWidth, 10)];
    seperateView.backgroundColor =UIColorFromRGB(0xdcdddd);
    [_bjImageview addSubview:seperateView];
    
}


- (void)thumbnailTapAction:(UIGestureRecognizer *)gesture{
    
    NSLog(@"更换头像");
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.tag = 10;
    [actionSheet showInView:self];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(actionSheet.tag == 10){
        
        //拍照
        if(buttonIndex == 0 ){
            
            [self photographByCarema];
            
        }
        //从相册选择
        else if(buttonIndex == 1){
            
            [self pirtureGetToCarema];
            
        }else if(buttonIndex == 2){
            actionSheet.hidden = YES;
        }
    }else{
        
    }
}

//拍照
-(void)photographByCarema{
    
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;//允许编辑，只有框里面的才显示
    imagePickerController.delegate = self;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self.viewController presentViewController:imagePickerController animated:YES completion:nil];
    }
    
}

//从相册选择
-(void)pirtureGetToCarema{
    
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;//允许编辑，只有框里面的才显示
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self.viewController  presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *image1 = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [UIImage saveImageToAlbum:image1] ;
    }
    
    [self uploadFile:image1];

    
    [picker dismissViewControllerAnimated:YES completion:nil];
}



- (void)uploadFile:(UIImage *)image{
    UpYun *uy = [[UpYun alloc] init];
    uy.successBlocker = ^(id data)
    {
        
//      http://twshop.b0.upaiyun.com/2014/12/1418190347.jpg
        NSString *strName = [NSString stringWithFormat:@"http://%@.b0.upaiyun.com%@",DEFAULT_BUCKET,self.imageStr];
        [_headerImageView setImageWithURL:[NSURL URLWithString:strName] placeholderImage:[UIImage imageNamed:@"carema_select"]];
         self.imageUrl = strName;
        [self setHeaderImageUrl:self.imageUrl];
        
        NSLog(@"%@",data);
    };
    
    uy.failBlocker = ^(NSError * error)
    {
        NSString *message = [error.userInfo objectForKey:@"message"];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"error" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        NSLog(@"%@",error);
    };
    
    //	@brief	根据 UIImage 上传
    
    UIImage* img = image;
    if (image.size.width>1000)
    {
        float scale = 1000.0/image.size.width ;
        img = [self imageWithImageSimple:image scaledToSize:CGSizeMake(1000, image.size.height*scale)];
        img = [UIImage imageWithImageSimple:img scaledToSize:CGSizeMake(60, 60)];
    }
    [uy uploadFile:img saveKey:[self getSaveKey]];
    
}

-(void)setHeaderImageUrl:(NSString *)imageUrl{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    SetValueForKey(dic, imageUrl, @"userIcon");
    SetValueForKey(dic, [RegisterHelper shareHelper].userId, @"userId");
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kUploadIcon
                             andHttpMethod:@"POST"
                             andParameters:dic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                        
                         request.requestCache = YES;
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             NSLog(@"成功数据:%@",responseDic);
                             [self showToastWithMessage:@"上传成功" showTime:2];
                         }
                     }];
}

-(NSString * )getSaveKey {
    /**
     *	@brief	方式1 由开发者生成saveKey
     */
    NSDate *d = [NSDate date];
    self.imageStr = [NSString stringWithFormat:@"/%d/%d/%.0f.jpg",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    return self.imageStr;
    
}

- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [picker dismissViewControllerAnimated:YES completion:nil];
    
}



-(void)setOtherModel:(OtherModel *)otherModel{
    

    _otherModel = otherModel;
    if ([self.otherModel.nickName isEqual:@"(null)"]||[self.otherModel.nickName isEqualToString:@""]) {
        _nickLabel.text = @"未知名";
        }else{
            _nickLabel.text = self.otherModel.nickName;
        }
        _focusNumLabel.text = [NSString stringWithFormat:@"%@",self.otherModel.score];
        
    NSURL *urlStr = [NSURL URLWithString:self.otherModel.userIcon];
    [_headerImageView setImageWithURL:urlStr placeholderImage:[UIImage imageNamed:@"carema_select"]];
    
}


-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = newSize.width;
    CGFloat targetHeight = newSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, newSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(newSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

-(void)loginViewAction{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(joinLoginVC)]) {
        [self.delegate joinLoginVC];
    }
}
@end
